package edu.aynu.service.impl;

import edu.aynu.dao.RoleDao;
import edu.aynu.dao.UserDao;
import edu.aynu.entity.Role;
import edu.aynu.entity.User;
import edu.aynu.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private RoleDao roleDao;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        User user = userDao.selectUserByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("账户不存在!");
        }
        List<Role> roles = new ArrayList<>();
        roles.add(roleDao.selectRoleById(user.getId()));
        user.setRoles(roles);

        return user;
    }

    @Override
    public User queryById(Integer id) {
        return userDao.queryById(id);
    }

    /**
     * 根据账号查找密码
     * @param user
     * @return
     */
    @Override
    public User queryOne(User user) {
        return userDao.queryOne(user);
    }

    @Override
    public User deterUsername(String username) {
        return userDao.deterUsername(username);
    }

    @Override
    public User deterEmail(String email) {
        return userDao.deterEmail(email);
    }

    @Override
    public int addUser(User user) {
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        return userDao.addUser(user);
    }

    @Override
    public int updateUserById(User user) {
        String password = passwordEncoder.encode(user.getPassword());
        user.setPassword(password);
        return userDao.updateUserById(user);
    }

    @Override
    public int deleteUserById(int id) {
        return userDao.deleteUserById(id);
    }

    /**
     * =================================管理员操作===============================================================
     */

    @Override
    public List<User> queryAll() {
        return userDao.queryAll();
    }

    @Override
    public int deleteUserByIds(Integer[] ids) {
        return userDao.deleteUserByIds(ids);
    }

}
